# Copyright (c) 2021 Presto Labs Pte. Ltd.
# Author: fengyang

import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo


def generate():
  mea = 'Futures.Gateio.v4'
  me = 'Futures.Gateio'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()

  pis = []
  data = []
  btc_futures = requests.get('https://api.gateio.ws/api/v4/futures/btc/contracts').json()
  data.extend(btc_futures)
  usdt_futures = requests.get('https://api.gateio.ws/api/v4/futures/usdt/contracts').json()
  data.extend(usdt_futures)
  for info in data:
    str_list = info['name'].split('_')
    if len(str_list) != 2:
      continue
    expiry = 'PERPETUAL'
    native_symbol = info['name']
    native_base = str_list[0]
    native_quote = str_list[1]
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)
    symbol = "%s-%s.%s" % (base, quote, expiry)

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        price_ticksize=float(info['order_price_round']),
        qty_ticksize=float(info['order_size_min']),
        contract_value=float(1) if info['type'] == 'inverse' else float(info['quanto_multiplier']),
        is_inverse=(info['type'] == 'inverse'),
    )

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


def gen_coin1_constants():
  data = generate()
  data = convert_coin1_constants(data)
  return data


def convert_coin1_constants(data):
  symbol_list = [info['native_symbol'] for info in data]
  quote_currency_list = [info['native_quote'] for info in data]
  base_currency_list = [info['native_base'] for info in data]
  currency_list = base_currency_list + quote_currency_list
  res = {
      'symbol_list': list(set(symbol_list)),
      'base_currency_list': list(set(base_currency_list)),
      'quote_currency_list': list(set(quote_currency_list)),
      'currency_list': list(set(currency_list)),
  }
  return res


if __name__ == "__main__":
  import json
  print(json.dumps(generate(), indent=2))
